<template>
  <div>
    <el-row align="middle" class="pt-20">
      <el-col :span="16">
        <p class="main_title">{{ $t('menu.USER') }}</p>
      </el-col>
    </el-row>
    <div style="display: flex; margin: 15px;0;15px;0">
      <div style="flex: 0 0 70%;padding-right: 5px;padding-left: 5px;" class="mb-4">
        <el-row class="search_block pt-5">
          <el-col :span="8">
            <el-input placeholder="请输入登录名" v-model="searchData.term" class="input-with-select" clearable @change="doList">
              <el-button slot="append" icon="el-icon-search" @click="doList">查询</el-button>
            </el-input>
          </el-col>
        </el-row>
      </div>
      <div style="flex: 0 0 25%;padding-right: 5px;padding-left: 5px;" class="mb-4">
        <div style="float:right">
          <el-button size="medium" type="primary" @click="addUser">{{ $t('button.ADDUSER') }} <i class="el-icon-circle-plus-outline"></i>
          </el-button>
        </div>
      </div>
    </div>

    <div class="table_container">
      <el-table :data="users" :header-cell-style="boxheader" :row-style="{height:0+'px'}" :cell-style="{padding:0+'px'}" style="width: 100%">
        <el-table-column min-width="50px" align="center" prop="userid" :label="$t('user.USERID')">
          <template slot-scope="scope">
            <span>{{ scope.row.userid}}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="80px" align="center" :label="$t('user.LOGINNAME')">
          <template slot-scope="scope">
            <span>{{ scope.row.loginname}}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="50px" align="center" label="用户类型">
          <template slot-scope="scope">
            <span v-if="scope.row.roleid === 0">普通用户</span>
            <span v-if="scope.row.roleid === 1">管理员</span>
          </template>
        </el-table-column>
        <el-table-column min-width="50px" align="center" prop="status" :label="$t('user.STATUS')">
          <template slot-scope="scope">
            <span class="priority_middle" v-if="scope.row.status == 0">{{$t('status.REGULAR')}}</span>
            <el-tag type="danger" effect="dark" v-if="scope.row.status != 0">{{$t('user.FORZEN')}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column min-width="120px" align="center" prop="logintime" :label="$t('user.LOGINTIME')">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.logintime).split(" ")[0]}} {{ parseTime(scope.row.logintime).split(" ")[1]}}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="80px" align="center" :label="$t('user.LOGINIP')">
          <template slot-scope="scope">
            <span>{{ scope.row.loginip}}</span>
          </template>
        </el-table-column>
        <!--<el-table-column min-width="80px" align="center" :label="$t('user.LOGINS')">-->
        <!--<template slot-scope="scope">-->
        <!--<span>{{ scope.row.logins == 0 ? $t('status.LOGOUT') : $t('status.LOGIN')}}</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column min-width="80px" align="center" :label="$t('common.OPER')">
          <template slot-scope="scope">
            <!--<el-button style="margin-left:0px !important;" type="text" @click="updateUser(scope.$index, scope.row)">{{ $t('common.UPDATE') }}</el-button>-->
            <el-button style="margin-left:0px !important;" type="text" @click="resetPwd(scope.row)">重置密码</el-button>
            <el-button v-if="scope.row.userid !== 1 && Number(userid) !== Number(scope.row.userid) " style="margin-left:0px !important;" type="text" @click="deleteUser(scope.row)">
              {{ $t('common.DELETE') }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="col-sm pt-3 text-sm-left" style="text-align:right; display: contents">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchData.curpage" :page-sizes="[5, 10, 20, 50]"
          :page-size="searchData.pagesize" layout="total, sizes,  pager, jumper" :total="searchData.total">
        </el-pagination>
      </div>
    </div>

    <el-dialog :title="$t('button.ADDUSER')" :visible.sync="addVisible" :width="width" :close-on-click-modal="false" class="addQuestion">
      <!-- :show-close="false" -->
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <el-form :model="addform" :rules="rules" ref="addform" label-width="120px">
        <el-form-item :label="$t('user.LOGINNAME')" prop="loginname">
          <el-input v-model="addform.loginname" :placeholder="$t('tips.ENTER.LOGINNAME')" style="width:70%"></el-input>
        </el-form-item>
        <el-form-item label="用户类型" style="clear:both; padding-top:30px" prop="roleid">
          <el-select v-model="addform.roleid" placeholder="请选择用户类型" class="inline">
            <el-option v-for="item in roles" :key="item.roleid" :label="item.rolename" :value="item.roleid">
            </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item :label="$t('user.TRUENAME')" prop="truename">-->
        <!--<el-input v-model="addform.truename" :placeholder="$t('tips.ENTER.TRUENAME')"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item :label="$t('user.MOBILENO')" style="clear:both" prop="mobileno">-->
        <!--<el-input v-model="addform.mobileno" :placeholder="$t('tips.ENTER.MOBILENO')"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item :label="$t('user.EMAIL')" style="clear:both" prop="email">-->
        <!--<el-input v-model="addform.email" :placeholder="$t('tips.ENTER.EMAIL')"></el-input>-->
        <!--</el-form-item>-->
        <!--<el-form-item :label="$t('user.ADDRESS')" style="clear:both" prop="address">-->
        <!--<el-input v-model="addform.address" :placeholder="$t('tips.ENTER.ADDRESS')"></el-input>-->
        <!--</el-form-item>-->
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align:center!important;">
        <el-button class="cancel_button" @click="addCancel('addform')">{{ $t('common.CANCEL') }}</el-button>
        <el-button class="confirm_button" @click="addSubmit('addform')">{{ $t('common.CONFIRM2') }}</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="$t('button.UPDATEUSER')" :visible.sync="updateVisible" :width="width" :close-on-click-modal="false" class="addQuestion">
      <img :src="iconImg" class="enlarge" @click="enlarge" width="12px" height="12px" />
      <el-form :model="updateform" :rules="updateRules" ref="updateform" label-width="120px">
        <el-form-item :label="$t('user.TRUENAME')" prop="truename">
          <el-input v-model="updateform.truename" :placeholder="$t('tips.ENTER.TRUENAME')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('user.MOBILENO')" style="clear:both" prop="mobileno">
          <el-input v-model="updateform.mobileno" :placeholder="$t('tips.ENTER.MOBILENO')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('user.EMAIL')" style="clear:both" prop="email">
          <el-input v-model="updateform.email" :placeholder="$t('tips.ENTER.EMAIL')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('user.ADDRESS')" style="clear:both" prop="address">
          <el-input v-model="updateform.address" :placeholder="$t('tips.ENTER.ADDRESS')"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align:center!important;">
        <el-button class="cancel_button" @click="updateCancel('updateform')">{{ $t('common.CANCEL') }}</el-button>
        <el-button class="confirm_button" @click="updateSubmit('updateform')">{{ $t('common.CONFIRM2') }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import adminService from "@/service/adminService";
import enlargeImg from "@/assets/images/icon_2.png";
import narrowImg from "@/assets/images/icon_3.png";
import i18n from "@/lang";
import { mapGetters } from "vuex";
import { getUserId } from "@/utils/auth";

export default {
  name: "UserList",
  data() {
    return {
      boxheader: {
        // background: '#eef1f6',
        color: "#606266",
        fontWeight: 800,
        borderBottom: "2px solid #EBEEF5",
      },
      searchData: {
        term: "",
        curpage: 1,
        pagesize: 10,
        total: 0,
      },
      userid: "",
      users: [],
      iconImg: enlargeImg,
      width: "600px",
      addVisible: false,
      updateVisible: false,
      addform: {
        roleid: "",
        loginname: "",
        truename: "",
        mobileno: "",
        email: "",
        address: "",
        password: "",
      },
      updateform: {
        truename: "",
        mobileno: "",
        email: "",
        address: "",
        password: "",
      },
      roles: [
        { roleid: 0, rolename: "普通成员" },
        { roleid: 1, rolename: "管理员" },
      ],
      rules: {
        roleid: [
          { required: true, message: "请选择用户类型", trigger: "blur" },
        ],
        loginname: [
          {
            required: true,
            message: i18n.t("valid.LOGINNAME.NOTNULL"),
            trigger: "blur",
          },
          {
            min: 2,
            max: 20,
            message: i18n.t("valid.LOGINNAME.SIZELIMIT"),
            trigger: "blur",
          },
        ],
        truename: [
          {
            required: true,
            message: i18n.t("valid.TRUENAME.NOTNULL"),
            trigger: "blur",
          },
          {
            min: 2,
            max: 20,
            message: i18n.t("valid.TRUENAME.SIZELIMIT"),
            trigger: "blur",
          },
        ],
        mobileno: [],
        email: [],
        address: [],
        password: [],
      },
      updateRules: {
        truename: [
          {
            required: true,
            message: i18n.t("valid.TRUENAME.NOTNULL"),
            trigger: "blur",
          },
          {
            min: 2,
            max: 20,
            message: i18n.t("valid.TRUENAME.SIZELIMIT"),
            trigger: "blur",
          },
        ],
        mobileno: [],
        email: [],
        address: [],
        password: [],
      },
      updateUserId: "",
    };
  },
  computed: {
    ...mapGetters(["userStat"]),
  },
  watch: {},
  mounted: function () {
    // commit('SET_ACTIVE', 1)
    this.$store.dispatch("setActive", "1").then(() => {});
    // localStorage.setItem('active', 1)
    this.userid = getUserId();
    // console.log(this.userid)
    adminService.list({ curpage: 1, pagesize: 10 }).then((res) => {
      if (res && res.data.result === 0) {
        this.users = res.data.data;
        this.searchData.total = res.data.total;
      }
    });
  },
  created() {},
  destroyed() {},
  methods: {
    clearAdduserForm() {
      this.addform = {
        truename: "",
        mobileno: "",
        email: "",
        address: "",
        password: "",
      };
    },
    /**
     * 打开新增用户对话框
     **/
    addUser() {
      this.addVisible = true;
      this.clearAdduserForm();
    },
    /**
     * 取消新增
     **/
    addCancel(addform) {
      this.addVisible = false;
      this.$refs[addform].resetFields();
    },

    /**
     * 提交新增
     **/
    addSubmit(addform) {
      this.$refs[addform].validate((valid) => {
        let dataInfo = {
          loginname: this.addform.loginname,
          truename: this.addform.truename,
          mobileno: this.addform.mobileno,
          email: this.addform.email,
          address: this.addform.address,
          password: this.addform.password,
          roleid: this.addform.roleid,
        };
        if (valid) {
          adminService.add(dataInfo).then((res) => {
            if (res && res.data.result === 0) {
              this.$message({
                message: i18n.t("tips.USER.ADDSUCCESS"),
                type: "success",
              });
              this.addVisible = false;
              this.listUser();
            }
          });
        } else {
          return false;
        }
      });
    },
    updateUser(index, row) {
      this.updateUserId = row.userid;
      this.updateVisible = true;
      this.updateform = {
        truename: row.truename,
        mobileno: row.mobileno,
        email: row.email,
        address: row.address,
        password: "",
      };
    },
    updateCancel() {
      this.updateVisible = false;
      this.updateUserId = "";
    },
    updateSubmit(updateform) {
      this.$refs[updateform].validate((valid) => {
        let dataInfo = {};
        dataInfo.userid = this.updateUserId;
        if (!this.ifnull(this.updateform.truename)) {
          dataInfo.truename = this.updateform.truename;
        }
        if (!this.ifnull(this.updateform.mobileno)) {
          dataInfo.mobileno = this.updateform.mobileno;
        }
        if (!this.ifnull(this.updateform.email)) {
          dataInfo.email = this.updateform.email;
        }
        if (!this.ifnull(this.updateform.address)) {
          dataInfo.address = this.updateform.address;
        }
        if (!this.ifnull(this.updateform.password)) {
          dataInfo.password = this.updateform.password;
        }
        if (valid) {
          adminService.update(dataInfo).then((res) => {
            if (res && res.data.result === 0) {
              this.$message({
                message: i18n.t("tips.USER.UPDATESUCCESS"),
                type: "success",
              });
              this.updateVisible = false;
              this.listUser();
            }
          });
        } else {
          return false;
        }
      });
    },
    deleteUser(row) {
      this.$confirm("是否删除用户 " + row.loginname + " ?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let dataInfo = {
            userid: row.userid,
          };
          adminService.delete(dataInfo).then((res) => {
            if (res && res.data.result === 0) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.listUser();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    resetPwd(row) {
      this.$confirm("是否重置用户 " + row.loginname + "的密码 ?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let dataInfo = {
            userid: row.userid,
          };
          adminService.resetPwd(dataInfo).then((res) => {
            if (res && res.data.result === 0) {
              this.$message({
                type: "success",
                message: "已重置!",
              });
              this.listUser();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    ifnull(data) {
      if (data == null || data == undefined || data == "") {
        return true;
      } else {
        return false;
      }
    },
    parseTime(data) {
      if (data == null) {
        return "";
      }
      // return parseTime(data, 'YYYY-MM-DD HH:mm:ss')
      return data;
    },
    /**
     * 弹窗放大缩小
     */
    enlarge() {
      if (this.width === "600px") {
        this.width = "1000px";
        this.iconImg = narrowImg;
      } else {
        this.width = "600px";
        this.iconImg = enlargeImg;
      }
    },
    /**
     * 改变分页大小
     * @param val 分页大小
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchData.pagesize = val;
      console.log(this.searchData.pagesize, "this.searchData.pagesize");
      this.listUser();
    },
    /**
     * 选择页码
     * @param val 当前页码
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.searchData.curpage = val;
      console.log(this.searchData.curpage, "this.searchData.curpage");
      this.listUser();
    },
    doList() {
      this.searchData.curpage = 1;
      this.listUser();
    },
    /**
     * 查询用户列表
     */
    listUser() {
      adminService.list(this.searchData).then((res) => {
        if (res && res.data.result === 0) {
          this.users = res.data.data;
          this.searchData.total = res.data.total;
        }
      });
    },
  },
};
</script>

<style>
.main_title {
  color: #343434;
  font-size: 18px;
  margin: 7px 0 0 0;
}
</style>
